from datetime import datetime
from typing import Optional, List
from fastapi import APIRouter, Query, HTTPException
from apps.schemas.schemas import StudentTrainingCreateRequest, StudentTrainingUpdateRequest
from apps.services.student_trainings import (
    get_student_trainings_by_user_id,
    get_all_student_trainings,
    get_student_training_by_id,
    create_student_training,
    update_student_training,
    delete_student_training
)

student_trainings = APIRouter()


@student_trainings.get("/trainings/user/{user_id}")
async def get_student_trainings_by_user_id_api(user_id: int):
    """
    根据用户ID获取学生训练记录（学生或教练）
    """
    try:
        result = await get_student_trainings_by_user_id(user_id)
        return {
            "status": 200,
            "message": "success",
            "data": result["data"],
            "total": result["total"],
            "user_id": result["user_id"],
            "user_type": result["user_type"],
            f"{result['user_type']}_id": result[f"{result['user_type']}_id"]
        }
    except ValueError as e:
        return {
            "status": 404,
            "message": str(e),
            "data": []
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Internal server error: {str(e)}",
            "data": []
        }


@student_trainings.get("/trainings")
async def get_all_student_trainings_api(
        student_id: Optional[int] = Query(None, description="Filter by student ID"),
        coach_id: Optional[int] = Query(None, description="Filter by coach ID"),
        program_id: Optional[int] = Query(None, description="Filter by program ID"),
        status: Optional[str] = Query(None, description="Filter by training status"),
        page: int = Query(1, ge=1),
        page_size: int = Query(10, ge=1, le=100)
):
    """
    获取所有学生训练记录（分页）
    """
    try:
        total, trainings_data = await get_all_student_trainings(
            student_id=student_id,
            coach_id=coach_id,
            program_id=program_id,
            status=status,
            page=page,
            page_size=page_size
        )
        return {
            "status": 200,
            "message": "success",
            "data": trainings_data,
            "total": total,
            "page": page,
            "page_size": page_size
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving student trainings: {str(e)}",
            "data": [],
            "total": 0,
            "page": page,
            "page_size": page_size
        }


@student_trainings.get("/trainings/{training_id}")
async def get_student_training_api(training_id: int):
    """
    根据训练ID获取学生训练记录
    """
    try:
        training_data = await get_student_training_by_id(training_id)
        if training_data:
            return {
                "status": 200,
                "message": "success",
                "data": training_data
            }
        else:
            return {
                "status": 404,
                "message": "Student training record not found",
                "data": {}
            }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving student training: {str(e)}",
            "data": {}
        }



@student_trainings.post("/trainings/add")
async def create_student_training_api(data: StudentTrainingCreateRequest):
    """
    创建新的学生训练记录
    """
    try:
        training = await create_student_training(data)
        return {
            "status": 201,
            "message": "Student training record created successfully",
            "data": {
                "training_id": training.training_id
            }
        }
    except ValueError as e:
        return {
            "status": 404,
            "message": str(e),
            "data": {}
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error creating student training record: {str(e)}",
            "data": {}
        }


@student_trainings.put("/trainings/update/{training_id}")
async def update_student_training_api(training_id: int, data: StudentTrainingUpdateRequest):
    """
    更新学生训练记录
    """
    try:
        updated = await update_student_training(training_id, data)
        if updated:
            return {
                "status": 200,
                "message": "Student training record updated successfully",
                "data": {}
            }
        else:
            return {
                "status": 404,
                "message": "Student training record not found",
                "data": {}
            }
    except ValueError as e:
        return {
            "status": 404,
            "message": str(e),
            "data": {}
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error updating student training record: {str(e)}",
            "data": {}
        }


@student_trainings.delete("/trainings/delete/{training_id}")
async def delete_student_training_api(training_id: int):
    """
    删除学生训练记录
    """
    try:
        deleted = await delete_student_training(training_id)
        if deleted:
            return {
                "status": 200,
                "message": "Student training record deleted successfully",
                "data": {}
            }
        else:
            return {
                "status": 404,
                "message": "Student training record not found",
                "data": {}
            }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error deleting student training record: {str(e)}",
            "data": {}
        }
